const Controller = require('egg').Controller;
const expireTime = '24h';

class UserController extends Controller {
  /* 前台 */
  async testName() {
    try {
      const { ctx } = this
      const { username } = ctx.request.body
      const data = await ctx.service.user.testName(username)
      if(data.length === 0) {
        ctx.body = {
          code: '0',
          desc: '该用户名可用~'
        }
      } else {
        return ctx.body = {
          code: '-1',
          desc: '对不起，该用户名重复~'
        }
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '获取用户列表失败',
        err: error
      }
    }
  }

  async register() {
    try {
      const { ctx } = this
      const { username, password } = ctx.request.body
      if (username && password) {
        try {
          const user = await ctx.service.user.findUser(username)
          if (user) {
            ctx.body = {
              code: '-1',
              desc: '用户已存在'
            }
            // 已注册用户自动登录，验证密码
            // 1表示已注册用户， 2表示新注册用户
            await this.login(ctx, 1)
          } else {
            const params = {
              password,
              username
            }
            await ctx.service.user.createUser(params)
            ctx.body = {
              code: 0,
              desc: '注册成功~',
              userInfo: {
                username: req.username
              }
            }
            // 注册成功后自动登录
            // 1表示已注册用户， 2表示新注册用户
            await this.login(ctx, 2)
          }
        } catch (error) {
          ctx.body = {
            code: '-1',
            desc: '注册失败~',
            err: error
          }
        }
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '注册请求返回错误',
        err: error
      }
    }
  }

  async login(ctx1, status) {
    try {
      let ctx
      if(ctx1) {
        ctx = ctx1
      } else {
        ctx = this.ctx
      }
      const { app } = this
      const { username, password } = ctx.request.body
      if (!username || !password) {
        ctx.body = {
          code: '-1',
          desc: '用户名或密码不能为空~'
        }
      } else {
        const user = await ctx.service.user.findUserPass(username)
        if (user) {
          if (ctx.helper.decrypt(password, user.password)) {
            //生成token，验证登录有效期
            const token = app.jwt.sign({
              username: username,
              password: password
            }, app.config.jwt.secret, { expiresIn: expireTime })
            ctx.body = {
              code: '0',
              token: token,
              expire: 2,
              userInfo: user,
              desc: status === 1 ? '登录成功，欢迎回来~' : '注册成功，已自动登录~'
            }
          } else {
            ctx.body = {
              code: '-1',
              desc: status === 1 ? '用户名或密码错误~' : '数据错误~'
            }
          }
        } else {
          ctx.body = {
            code: '-1',
            desc: '尚未注册~'
          }
        }
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '登录请求返回错误',
        err: error
      }
    }
  }

  // 根据用户名搜索用户
  async searchUserInfo(){
    try {
      const { app, ctx } = this
      const { Op } = app.Sequelize
      const { username } = ctx.request.body
      const detail = await ctx.model.User.findAll({
        attributes:['username', 'id', 'avatar'],
        where: {
          username: {
            [Op.startsWith]: username
          }
        }
      })
      ctx.body = {
        code: '0',
        detail: detail,
        desc: '用户数据获取成功'
      }
    } catch(err) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '用户数据获取失败'
      }
    }
  }

  async getUserInfo(){
    try {
      const { ctx } = this
      const { username } = ctx.request.body
      if (!username) {
        ctx.body = {
          code: '-1',
          desc: '请求缺少参数'
        }
      } else {
        const user = await ctx.service.user.findUser(username)
        if (username == user.username) {
          ctx.body = {
            code: '0',
            userInfo: user,
            desc: '用户信息获取成功'
          }
        }
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '用户信息请求返回错误',
        err: error
      }
    }
  }

  async getUserIdInfo(){
    try {
      const { ctx } = this
      const { id } = ctx.request.body
      if (!id) {
        ctx.body = {
          code: '-1',
          desc: '请求缺少参数'
        }
      } else {
        const user = await ctx.service.user.findUserId(id)
        if (id == user.id) {
          ctx.body = {
            code: '0',
            userInfo: user,
            desc: '用户信息获取成功'
          }
        }
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '用户信息请求返回错误',
        err: error
      }
    }
  }

  /* 后台 */
  async getUsers() {
    try {
      const { app, ctx } = this;
      const { Op } = app.Sequelize;
      const { searchForm, page, limit } = ctx.request.body;
      let conditions = {}
      // 搜索
      if(!searchForm) {
      } else {
        if(!!searchForm.username) {
          conditions.username = {[Op.startsWith]: searchForm.username};
        } 
        if(!!searchForm.nickname) {
          conditions.nickname = {[Op.startsWith]: searchForm.nickname};
        }
        if(!!searchForm.type) {
          conditions.type = searchForm.type;
        } 
        if(!!searchForm.phone) {
          conditions.phone = searchForm.phone;
        }
      }
      const pageOffset = ctx.helper.toInt((page - 1) * limit);
      const pageLimit = ctx.helper.toInt(limit);
      const users = await ctx.service.user.findList({
        where: conditions,
        limit: pageLimit,
        offset: pageOffset
      })
      ctx.body = {
        code: '0',
        desc: '获取用户列表成功',
        users: users.rows,
        count: users.count
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '获取用户列表失败',
        err: error
      }
    }
  }

  async createUser() {
    try {
      const { ctx } = this
      const req = ctx.request.body
      req.password = ctx.helper.encrypt(req.password)
      await ctx.service.user.createUser(req)
      ctx.body = {
        code: '0',
        desc: '用户添加成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '用户添加失败',
        err: error
      }
    }
  }

  async editUser() {
    try {
      const { ctx } = this
      const { userForm, id } = ctx.request.body
      await ctx.service.user.editUser(userForm, id)
      ctx.body = {
        code: '0',
        desc: '用户修改成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '用户修改失败',
        err: error
      }
    }
  }

  async deleteUser() {
    try {
      const { ctx } = this
      const { id } = ctx.request.body
      await ctx.service.user.deleteUser(id)
      ctx.body = {
        code: '0',
        desc: '用户删除成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '用户删除失败',
        err: error
      }
    }
  }

   async batchDeleteUsers() {
    try {
      const { ctx } = this
      const { ids } = ctx.request.body
      await ctx.service.user.batchDeleteUsers(ids)
      ctx.body = {
        code: '0',
        desc: '用户批量删除成功'
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '用户批量删除失败',
        err: error
      }
    }
  }

  async adminLogin() {
    try {
      const { app, ctx } = this;
      const { username, password } = ctx.request.body;
      if (!username || !password) {
        ctx.body = {
          code: '-1',
          desc: '用户名或密码不能为空'
        }
      } else {
        const user = await ctx.service.user.findUserPass(username)
        if (user) {
            if (ctx.helper.decrypt(password, user.password)) {
              //判断是否是管理员
              if(user.type === 'admin') {
                //生成token，验证登录有效期
                const token = app.jwt.sign({
                  username: username,
                  password: password
                }, app.config.jwt.secret, { expiresIn: expireTime })
                ctx.body = {
                  code: '0',
                  token: token,
                  expire: 2,
                  adminInfo: user,
                  desc: '登录成功，欢迎回来~'
                }
              } else {
                ctx.body = {
                  code: '-1',
                  desc: '暂无登录权限~'
                }
              }
            } else {
              ctx.body = {
                code: '-1',
                desc: '用户名或密码错误'
              }
            }
        } else {
          ctx.body = {
            code: '-1',
            desc: '管理员不存在'
          }
        }
      }
    } catch(error) {
      const { ctx } = this
      ctx.body = {
        code: '-1',
        desc: '登录失败',
        err: error
      }
    }
  }
}

module.exports = UserController;